/**
 *
 */
package idao.engine.parameter;

import idao.DaoRuntimeException;
import ognl.Ognl;
import ognl.OgnlException;

/**
 * Implementations for parameters like "?1.property.nestedProperty"
 * 
 * @author huhao
 */
class ArgIndexThenOgnlParameter extends SqlParameter
{

    private int argIndex;
    private Object expression;

    public ArgIndexThenOgnlParameter(int parameterIndex, String parameterExpression)
    {
        super(parameterIndex, parameterExpression);
        int dotIdx = parameterExpression.indexOf('.');
        argIndex = Integer.parseInt(parameterExpression.substring(0, dotIdx)) - 1;
        try {
            expression = Ognl.parseExpression(parameterExpression.substring(dotIdx + 1));
        } catch (OgnlException e) {
            throw new DaoRuntimeException("Invalid OGNL expression '" + parameterExpression + "'.",
                            e);
        }
    }

    @Override
    protected Object getParameterValue(Object[] args)
    {
        try {
            return Ognl.getValue(expression, args[argIndex]);
        } catch (OgnlException e) {
            throw new DaoRuntimeException("Failed to get parameter value.", e);
        }
    }

}
